<template>
    <div class="app-container">
      <el-card style="height: 100%; overflow-y: auto">
        <el-form ref="form" :rules="rulesForm" :model="form" label-width="120px">
          <!--        <el-form-item label="文章类型：" prop="type">-->
          <!--          <el-radio-group style="width: 1000px" v-model="form.type">-->
          <!--            <el-radio :label="1">普通文章</el-radio>-->
          <!--            &lt;!&ndash;            <el-radio :label="3">视频文章</el-radio>&ndash;&gt;-->
          <!--          </el-radio-group>-->
          <!--        </el-form-item>-->
          <el-form-item label="文章标题：" prop="title">
            <el-input
              maxlength="64"
              show-word-limit
              style="width: 1000px"
              v-model="form.title"
            />
          </el-form-item>
          <!--        <el-form-item label="作者：" prop="author">-->
          <!--          <el-input style="width: 1000px" v-model="form.author" />-->
          <!--        </el-form-item>-->
          <el-form-item label="分类：" prop="cateId">
            <el-cascader
              style="width: 1000px"
              v-model="form.cateId"
              :options="cateList"
              :props="props"
              clearable
            />
          </el-form-item>
  
          <el-form-item label="发布账号：">
            <el-select style="width: 1000px" v-model="form.memberId">
              <el-option
                v-for="item in adminList"
                :key="item.id"
                :label="item.officialAuthnName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
  
          <el-form-item label="摘要：" prop="summary">
            <el-input
              type="textarea"
              rows="3"
              maxlength="120"
              show-word-limit
              style="width: 1000px"
              v-model="form.summary"
            />
          </el-form-item>
  
          <el-form-item
            label="关联产品："
            label-width="120px"
            style="display: inline-block"
          >
            <div style="">
              <div class="product-img">
                <div
                  class="product-img-box"
                  v-for="(item, idx) in form.relation"
                  :key="item.id"
                >
                  <el-tooltip effect="dark" :content="item.name" placement="top">
                    <img style="" :src="item.pic" />
                  </el-tooltip>
  
                  <i
                    @click="delProduct(idx, item.id)"
                    style="color: #ccc; font-weight: bold"
                    class="el-icon-close i2"
                  ></i>
                </div>
  
                <div style="line-height: 96px; margin-right: 10px">
                  <div class="uploadPic" @click="selectPic()">
                    <i
                      style="
                              font-size: 40px;
                              color: #ccc;
                              font-weight: bold;
                            "
                      class="el-icon-plus i1"
                    ></i>
                  </div>
                </div>
              </div>
              <div style="color: #222; font-size: 14px">选择产品</div>
            </div>
          </el-form-item>
          <el-form-item label="封面图："  v-if="form.type == 1">
            <div style="display: flex">
              <single-upload
                uploadType="2"
                v-model="form.imageUrl"
                :width="'220px'"
                :height="'140px'"
                :border="'1px solid #ccc'"
              >
                <div
                  class=""
                  style="line-height: 140px;margin-top: 8px"
                  v-if="!form.pic"
                >
                  <i
                    style="font-size: 40px; color: #ccc; font-weight: bold"
                    class="el-icon-plus"
                  ></i>
                </div>
              </single-upload>
  
              <div
                style="margin-left: 20px; color: #aaa; line-height: 30px;margin-top: 20px; font-size: 14px"
              >
                <div>温馨提示</div>
                <div>1、支持jpg、jpeg、png格式的图片文件</div>
                <div>2、尺寸比较建议长宽660*420，大小限制在2M以下</div>
              </div>
            </div>
          </el-form-item>
          <div
            :style="{ 'margin-top': form.image ? '0' : '30px' }"
            v-if="form.type == 1"
          >
            <el-form-item label="文章内容：" prop="content">
              <Tinymce ref="tinymce" v-model="form.content" :height="600" />
            </el-form-item>
          </div>
          <el-form-item label="关联视频：" v-if="form.type == 3" prop="linkUrl">
            <uploadVideo
              cateId="1000601451"
              v-model="form.linkUrl"
              @editVideoId="editVideoId"
            ></uploadVideo>
          </el-form-item>
          <el-form-item label="热门话题：" prop="hotTopicId">
            <el-select style="width: 1000px" v-model="form.hotTopicId" multiple>
              <el-option
                v-for="item in hotList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="是否置顶：" prop="topStatus">
            <el-radio-group style="width: 1000px" v-model="form.topStatus">
              <el-radio :label="0">不置顶</el-radio>
              <el-radio :label="1">置顶</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="封面图："
            prop="sourceUrl"
            v-if="form.topStatus == 1"
          >
            <div style="display: flex; ">
              <single-upload
                uploadType="2"
                @uploadSucces="uploadSucces"
                v-model="form.sourceUrl"
              >
                <div class="uploadPic2" v-if="!form.sourceUrl">
                  <i
                    style="font-size: 40px; color: #ccc; font-weight: bold"
                    class="el-icon-plus"
                  ></i>
                </div>
              </single-upload>
              <div style="margin-top: 50px; color: #999">
                * 置顶文章需要上传封面图 (封面规格：350*120)
              </div>
            </div>
          </el-form-item>
          <el-form-item
            label="置顶截止时间："
            prop="topTime"
            v-if="form.topStatus == 1"
          >
            <el-date-picker
              v-model="form.topTime"
              type="datetime"
              placeholder="选择日期时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="pickerOptions1"
            />
          </el-form-item>
          <el-form-item label="是否首页推荐：" prop="recommendStatus">
            <el-radio-group style="width: 1000px" v-model="form.recommendStatus">
              <el-radio :label="0">不推荐</el-radio>
              <el-radio :label="1">推荐</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否可以评论" prop="commentStatus">
            <el-radio-group style="width: 1000px" v-model="form.commentStatus">
              <el-radio :label="0">禁止评论</el-radio>
              <el-radio :label="1">允许评论</el-radio>
            </el-radio-group>
          </el-form-item>
  
          <el-form-item label="是否发布：">
            <el-radio-group style="width: 1000px" v-model="form.publishStatus">
              <el-radio :label="1">立即发布</el-radio>
              <el-radio :label="0">定时发布</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="发布时间："
            prop="publishTime"
            v-if="form.publishStatus == 0"
          >
            <el-date-picker
              v-model="form.publishTime"
              type="datetime"
              placeholder="选择日期时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="pickerOptions"
            />
          </el-form-item>
          <el-form-item>
            <div style="margin-left: 350px">
              <el-button
                style="width: 100px"
                type="primary"
                @click="onSubmit('form', 2)"
                >发布</el-button
              >
              <el-button
                v-if="form.publishStatus == 0"
                style="width: 100px"
                @click="onSubmit('form', 1)"
                >暂存</el-button
              >
              <el-button @click="goBack()" style="width: 100px">返回</el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </template>
  
  <script>
  import uploadVideo from "@/components/uploadVideo/uploadVideo";
  import Tinymce from "@/components/Tinymce";
  import SingleUpload from "@/components/Upload/uploadOne";
  import {
    getArticleListTree,
    addArticle,
    getArticleInfo,
    editArticle,
    getLinkAccountlist,
    getHotTopicList
  } from "@/api/article";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import { pickerOptions } from "../product/options";
  const form = {
    title: "", //文章标题
    // author: "", //作者
    cateId: null, //分类id
  
    summary: "",
    productIdList: [],
    relation: [], //关联产品id
    imageUrl: "",
    content: "",
    memberId: "", //发布账号
    hotTopicId: [], //热门话题
    topStatus: 1, //是否置顶 0->未置顶；1->置顶
    topTime: "", // 置顶截止时间
    publishStatus: 1, //是否显示
    publishTime: "", //发布时间
    sourceType: 0, //sourceType
    type: 1,
    videoId: "",
    linkUrl: "",
    sourceUrl: "", //置顶封面图
    commentStatus: 0, //是否可以评论：0->不可以；1->可以
    recommendStatus: 1 //推荐状态：0->首页不推荐；1->首页推荐"
  };
  export default {
    name: "add",
    components: { SingleUpload, Tinymce, Treeselect, uploadVideo },
    data() {
      return {
        props: {
          emitPath: false
        },
  
        form: Object.assign({}, form),
        rulesForm: {
          title: [
            { required: true, message: "请输入文章标题", trigger: "blur" },
            { min: 1, max: 64, message: "长度在 1 到 64 个字符", trigger: "blur" }
          ],
          author: [{ required: true, message: "请输入作者", trigger: "blur" }],
          cateId: [{ required: true, message: "请选择分类", trigger: "blur" }],
          publishStatus: [
            { required: true, message: "请选择是否显示", trigger: "blur" }
          ],
          imageUrl: [
            { required: true, message: "请上传封面图", trigger: "blur" }
          ],
          content: [
            { required: true, message: "请输入文章内容", trigger: "blur" }
          ],
          memberId: [
            { required: true, message: "请选择发布账号", trigger: "blur" }
          ],
          summary: [{ required: true, message: "请输入摘要", trigger: "blur" }],
          publishTime: [
            {
              required: true,
              message: "请选择发布时间",
              trigger: "blur"
            }
          ],
          topTime: [
            { required: true, message: "请选择置顶时间", trigger: "blur" }
          ],
          hotTopicId: [
            { required: true, message: "请选择热门话题", trigger: "blur" }
          ],
          linkUrl: [
            { required: true, message: "请选择关联视频", trigger: "blur" }
          ],
          sourceUrl: [
            {
              required: true,
              message: "请选择置顶封面图",
              trigger: "blur"
            }
          ]
        },
        cateList: [],
        adminList: [],
        hotList: [],
        pickerOptions: {
          disabledDate(time) {
            // 获取今天的日期
            let today = new Date();
            today.setHours(0, 0, 0, 0); // 设置为当天的午夜 00:00:00
  
            // 获取20天后的日期
            let twentyDaysLater = new Date();
            twentyDaysLater.setDate(today.getDate() + 20);
            twentyDaysLater.setHours(23, 59, 59, 999); // 设置为20天后的当天的23:59:59
  
            // 返回是否在允许范围内
            return (
              time.getTime() < today.getTime() ||
              time.getTime() > twentyDaysLater.getTime()
            );
          }
        },
        pickerOptions1: {
          disabledDate(time) {
            // 获取当前时间的时间戳
            let now = Date.now();
  
            // 获取今天的日期的午夜时间戳
            let today = new Date();
            today.setHours(0, 0, 0, 0);
            let todayMidnight = today.getTime();
  
            // 返回是否在允许范围内，大于等于今天的日期即可
            return time.getTime() < todayMidnight;
          }
        }
        // videoUrl: "108621bb3ab671efbfc75017f0f90102"
      };
    },
    created() {
      this.getCateList();
      this.getLinkAccountlist();
      this.getHotTopicList();
      if (this.$route.query.id) {
        this.getInfo();
      }
    },
    mounted() {},
    methods: {
      uploadSucces() {},
      goBack() {
        this.$router.go(-1);
      },
      editVideoId(v) {
        this.form.videoId = v;
      },
      getHotTopicList() {
        getHotTopicList().then(res => {
          this.hotList = res.data;
        });
      },
      getLinkAccountlist() {
        getLinkAccountlist().then(res => {
          this.adminList = res.data;
        });
      },
      getInfo() {
        getArticleInfo(this.$route.query.id).then(res => {
          console.log(res.data);
          res.data.relation = JSON.parse(res.data.relation).map(v => {
            return {
              id: v.id,
              name: v.name,
              pic: v.pic
            };
          });
  
          res.data.productIdList = res.data.productList.map(v => {
            return v.id;
          });
          res.data.hotTopicId = res.data.articleHotTopicList.map(v => {
            return v.hotTopicId;
          });
  
          this.form = Object.assign({}, res.data);
          this.$refs.tinymce.setContent(this.form.content);
        });
      },
      /** 转换部门数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.id,
          label: node.label,
          children: node.children
        };
      },
      getCateList() {
        getArticleListTree().then(res => {
          this.cateList = res.data;
        });
      },
      selectPic() {
        let that = this;
        that.$modalGoodList(
          function(row) {
            if (row) {
              let app = row.map(v => {
                return {
                  id: v.id,
                  name: v.name,
                  pic: v.pic
                };
              });
              that.$set(that.form, "relation", app);
              this.$set(
                that.form,
                "productIdList",
                row.map(v => {
                  return v.id;
                })
              );
            }
          },
          3,
          that.form.productIdList
        );
      },
      delProduct(idx, id) {
        console.log(idx, id, this.form.relation);
        // return;
        this.form.productIdList.splice(idx, 1);
        const i = this.form.relation.findIndex(v => {
          return v.id === id;
        });
  
        if (i != -1) {
          this.form.relation.splice(i, 1);
        }
      },
      onSubmit(form, type) {
        //tasksStatus   1->暂存未发布；2->定时发布；3->取消定时发布；4->已发布
        this.$refs[form].validate(valid => {
          if (valid) {
            let params = JSON.parse(JSON.stringify(this.form));
            if (params.relation) {
              console.log(params.relation);
              params.relation = JSON.stringify(params.relation);
            }
            if (params.productList) {
              delete params.productList;
            }
            if (params.publishStatus != 1) {
              // 判断是否立即发布
              params.tasksStatus = type;
              // delete params.publishStatus;
            } else {
              delete params.tasksStatus;
            }
            params.hotTopicId = params.hotTopicId.join(",");
            if (this.$route.query.id) {
              editArticle(params).then(res => {
                if (res.code == 200) {
                  this.$message({
                    message: "编辑成功",
                    type: "success"
                  });
                  setTimeout(() => {
                    this.$router.go(-1);
                  }, 1000);
                }
              });
            } else {
              addArticle(params).then(res => {
                if (res.code == 200) {
                  this.$message({
                    message: "发布成功",
                    type: "success"
                  });
                  setTimeout(() => {
                    this.$router.go(-1);
                  }, 1000);
                }
              });
            }
          }
        });
      }
    }
  };
  </script>
  
  <style scoped lang="scss">
  .app-container {
    height: calc(100vh - 50px);
    background-color: #f5f5f5;
    position: relative;
  }
  .image-message {
    height: 96px;
    //display: flex;
  
    > div {
      &:nth-child(2) {
        //margin-right: 20px;
        //width: 500px;
      }
    }
  }
  .product-img {
    width: 1000px;
    display: flex;
    flex-wrap: wrap;
    .product-img-box {
      position: relative;
      .i2 {
        position: absolute;
        right: -1px;
        top: -5px;
      }
    }
    .uploadPic {
      width: 96px;
      height: 96px;
      // margin-left: 10px;
      background: #eeeeee;
      border-radius: 8px;
      position: relative;
  
      .i1 {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
      }
    }
  
    img {
      width: 96px;
      height: 96px;
      margin-right: 13px;
    }
  }
  .imageBg {
    width: 220px;
    height: 140px;
    line-height: 140px;
    background: #fff;
    border-radius: 8px;
    border: 1px solid #ddd;
  }
  .uploadPic1 {
    min-width: 96px;
    height: 96px;
    // margin-left: 10px;
    background: #fff;
    border-radius: 8px;
    position: relative;
    border: 1px solid #eee;
  
    .i1 {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }
  }
  .uploadPic2 {
    width: 90px;
    height: 90px;
  
    background: #eeeeee;
    border-radius: 8px;
    position: relative;
    > i {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }
  }
  </style>
  